import Bxios from './bxios'
import { useUserStore } from '@/store/modules/user'
import { useStoreInfoStore } from '@/store/modules/storeInfo'
import { useOrderStoreMap } from '@/store/modules/order'
// import { useSettingStore } from '@/store/modules/setting'
const bxios = new Bxios({
    baseUrl: import.meta.env.VITE_BASE_URL,
    header: {
        'Device-Id': uni.getSystemInfoSync().deviceId,
        'Client-Type': 'STORE',
        'Shop-Id': 0,
        // WECHAT_MINI_APP
        // Platform: 'WECHAT_MINI_APP',
        Platform: 'H5',
    },
})
const notNeedTokenList = [
    'gruul-mall-uaa/uaa/auth/captcha/slider',
    'gruul-mall-uaa/uaa/auth/captcha/sms',
    '/gruul-mall-uaa/login?grant_type=sms_code',
    '/gruul-mall-uaa/login?grant_type=password',
]
bxios.interceptors.request.use(
    (conf) => {
        const shopId = useStoreInfoStore().shopStoreInfo?.shopId || 0
        if (shopId) {
            conf.header['Shop-Id'] = shopId
        }
        // useSettingStore().SET_SHOP_ID(conf.header['Shop-Id'])
        const token = useUserStore().token
        if (!notNeedTokenList.includes(conf.url!) && token) {
            conf.header.Authorization = token
        } else {
            conf.header.Authorization = ''
        }
        return conf
    },
    (err) => {
        return Promise.reject(err)
    },
)
bxios.interceptors.response.use<any>(
    (res) => {
        if (res.code === 300005 || res.code === 2 || res.code === 3 || res.code === 4) {
            const $store = useUserStore()
            const $useOrderStoreMap = useOrderStoreMap()
            const $useStoreInfoStore = useStoreInfoStore()
            $store.REMOVE_TOKEN()
            $useOrderStoreMap.REMOVE_ORDER_MAP()
            $useStoreInfoStore.REMOVE_STORE_INFO()
            uni.reLaunch({ url: '/pages/sign/Index' })
        }
        return Promise.resolve(res)
    },
    (err) => {
        uni.showToast({
            icon: 'none',
            title: err || '服务器内部错误',
        })
        return Promise.reject(err)
    },
)
export default bxios
